package cn.edu.zstu.overlappingdisappear.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import cn.edu.zstu.overlappingdisappear.R;
import cn.edu.zstu.overlappingdisappear.api.UserApi;
import cn.edu.zstu.overlappingdisappear.base.App;
import cn.edu.zstu.overlappingdisappear.base.BaseActivity;
import cn.edu.zstu.overlappingdisappear.base.MyApplication;
import cn.edu.zstu.overlappingdisappear.bean.MatchResultBean;

/**
 * @Author ZhuMingWei(986990501@qq.com)
 * @Date on 2019/12/8
 * @Version v1.0.0
 * @Company TODO
 * @Describle TODO
 */

public class PKActivity extends BaseActivity implements View.OnClickListener {

    private AlertDialog matchDialog;
    private boolean isMatch = false;
    private ImageView btnPK;
    private ImageView btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pk);
        initView();
    }

    private void initView() {
        btnBack = findViewById(R.id.btn_back);
        btnPK = findViewById(R.id.btn_pk);
        btnBack.setOnClickListener(this);
        btnPK.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_pk:
                matchDialog = showMatchingDialog();
                isMatch = true;
                UserApi.match(App.Username, new UserApi.VolleyStrHandler() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MyApplication.getInstance(),"网络连接异常", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(String responseStr) {
                        try {
                            JSONObject reponse = new JSONObject(responseStr);
                            int status = reponse.getInt("code");
                            String msg=reponse.getString("msg");
                            String data=reponse.getString("data");
                            if (status == 1) {
                                MatchResultBean mrb =  new Gson().fromJson(data.toString(), new TypeToken<MatchResultBean>() {
                                }.getType());
                                App.RoomID = mrb.roomid;
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        while (isMatch){
                                            UserApi.searchRoomState(App.RoomID, new UserApi.VolleyStrHandler() {
                                                @Override
                                                public void onErrorResponse(VolleyError error) {
                                                    Toast.makeText(MyApplication.getInstance(),"网络连接异常", Toast.LENGTH_LONG).show();
                                                }

                                                @Override
                                                public void onResponse(String responseStr) {
                                                    try {
                                                        JSONObject reponse = new JSONObject(responseStr);
                                                        int code = reponse.getInt("code");
                                                        String msg=reponse.getString("msg");
                                                        String data=reponse.getString("data");
                                                        if(1 == code){
                                                            int status = reponse.getInt("status");
                                                            if(2 == status){
                                                                MatchResultBean mrb =  new Gson().fromJson(data.toString(), new TypeToken<MatchResultBean>() {
                                                                }.getType());
                                                                App.Room = mrb;
                                                                isMatch = false;
                                                                if(matchDialog!=null)
                                                                    matchDialog.dismiss();
                                                                showMatchedDialog();
                                                            }
                                                        }
                                                    } catch (JSONException e) {

                                                    }
                                                }
                                            });
                                            try {
                                                Thread.sleep(App.SleepTime);
                                            } catch (Exception e){

                                            }
                                        }
                                    }
                                }).start();
                            }else if(2 == status){
                                MatchResultBean mrb =  new Gson().fromJson(data.toString(), new TypeToken<MatchResultBean>() {
                                }.getType());
                                //mrb.init = "[[{\"x\":11,\"y\":4},{\"x\":14,\"y\":4},{\"x\":14,\"y\":7},{\"x\":11,\"y\":7}],[{\"x\":7,\"y\":8},{\"x\":10,\"y\":8},{\"x\":10,\"y\":11},{\"x\":7,\"y\":11}],[{\"x\":3,\"y\":12},{\"x\":6,\"y\":12},{\"x\":6,\"y\":15},{\"x\":3,\"y\":15}]]";
                                //mrb.goal = "[[{\"x\":7,\"y\":7},{\"x\":10,\"y\":7},{\"x\":10,\"y\":10},{\"x\":7,\"y\":10}],[{\"x\":8,\"y\":7},{\"x\":11,\"y\":7},{\"x\":11,\"y\":10},{\"x\":8,\"y\":10}],[{\"x\":6,\"y\":7},{\"x\":9,\"y\":7},{\"x\":9,\"y\":10},{\"x\":6,\"y\":10}]]";
                                App.RoomID = mrb.roomid;
                                App.Room = mrb;
                                if(matchDialog!=null)
                                    matchDialog.dismiss();
                                showMatchedDialog();
                            }
                        } catch (Exception e) {

                        }
                    }
                });
                break;
            case R.id.btn_back:
                finish();
                break;
        }
    }

    private AlertDialog showMatchingDialog() {
        final AlertDialog alertMatching = new AlertDialog.Builder(PKActivity.this).create();
        alertMatching.show();
        alertMatching.getWindow().setContentView(R.layout.dialog_matching);//重用布局文件

        Button btn_cancel = alertMatching.getWindow().findViewById(R.id.btn_cancel);

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMatch = false;
                alertMatching.dismiss();
                UserApi.cancelAll();
            }
        });
        return alertMatching;
    }

    private void showMatchedDialog() {
        final AlertDialog alertMatched = new AlertDialog.Builder(PKActivity.this).create();
        alertMatched.show();
        alertMatched.getWindow().setContentView(R.layout.dialog_matched);//重用布局文件

        final ImageView man1 = alertMatched.getWindow().findViewById(R.id.iv_man1);
        final ImageView vs = alertMatched.getWindow().findViewById(R.id.iv_vs);
        final ImageView man2 = alertMatched.getWindow().findViewById(R.id.iv_man2);
        Animation translateAnimation = new TranslateAnimation(-700,0,0,0);//平移动画  从0,0,平移到100,100
        translateAnimation.setDuration(500);//动画持续的时间为1.5s
        man1.setAnimation(translateAnimation);//给imageView添加的动画效果
        translateAnimation.setFillEnabled(true);//使其可以填充效果从而不回到原地
        translateAnimation.setFillAfter(true);//不回到起始位置
        //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
        translateAnimation.setAnimationListener(
                new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {//开始时
                        man1.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {//结束时
                        Animation translateAnimation2 = new TranslateAnimation(700,0,0,0);//平移动画  从0,0,平移到100,100
                        translateAnimation2.setDuration(500);//动画持续的时间为1.5s
                        vs.setAnimation(translateAnimation2);//给imageView添加的动画效果
                        translateAnimation2.setFillEnabled(true);//使其可以填充效果从而不回到原地
                        translateAnimation2.setFillAfter(true);//不回到起始位置
                        //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
                        translateAnimation2.setAnimationListener(
                                new Animation.AnimationListener() {
                                    @Override
                                    public void onAnimationStart(Animation animation) {//开始时
                                        vs.setVisibility(View.VISIBLE);
                                    }

                                    @Override
                                    public void onAnimationEnd(Animation animation) {//结束时
                                        Animation translateAnimation3 = new TranslateAnimation(700,0,0,0);//平移动画  从0,0,平移到100,100
                                        translateAnimation3.setDuration(500);//动画持续的时间为1.5s
                                        man2.setAnimation(translateAnimation3);//给imageView添加的动画效果
                                        translateAnimation3.setFillEnabled(true);//使其可以填充效果从而不回到原地
                                        translateAnimation3.setFillAfter(true);//不回到起始位置
                                        //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
                                        translateAnimation3.setAnimationListener(
                                                new Animation.AnimationListener() {
                                                    @Override
                                                    public void onAnimationStart(Animation animation) {//开始时
                                                        man2.setVisibility(View.VISIBLE);
                                                    }

                                                    @Override
                                                    public void onAnimationEnd(Animation animation) {//结束时

                                                    }

                                                    @Override
                                                    public void onAnimationRepeat(Animation animation) {//进行时

                                                    }
                                                });
                                        translateAnimation3.startNow();//动画开始执行 放在最后即可

                                    }

                                    @Override
                                    public void onAnimationRepeat(Animation animation) {//进行时

                                    }
                                });
                        translateAnimation2.startNow();//动画开始执行 放在最后即可
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {//进行时

                    }
                });
        translateAnimation.startNow();//动画开始执行 放在最后即可

        new Handler().postDelayed(new Runnable() {
            public void run() {
                alertMatched.dismiss();
                Intent it = new Intent(PKActivity.this,ChainActivity.class);
                it.putExtra("TYPE","Match");
                startActivity(it);
            }
        }, 2000);
    }
}
